#!/usr/bin/env python

import optparse
import sqlite3
import os

class DataBase:
    
    def __init__(self):
        self.conn = sqlite3.connect('/etc/webstatus/domains.db',
                                    isolation_level='exclusive')
        self.c = conn.cursor()
        

    def insert(self, website):
        """Inserts the url record into the database"""
        command = "INSERT INTO domains VALUES('%s')" % website
        self.c.execute(command)
        self.conn.commit()
        self.c.close()

    def delete(self, website):
        """Deletes the url record from the databse"""
        command = "DELETE FROM domains where name = ('%s')" % website
        self.c.execute(command)
        self.conn.commit()
        self.c.close()

    def query(self):
        """ Lists the domains in the database """
        command = "SELECT * FROM domains"
        return self.c.execute(command)

def main():
    p = optparse.OptionParser()
    p.add_option('--insert', '-i', help="insert a value")
    p.add_option('--delete', '-d', help="delete a value")
    p.add_option('--query', '-q', action="store_true",
                dest="query", help="query the domains table")
    options, args = p.parse_args()
    
    if os.path.isfile('/etc/websstatus/domains.db'):
        db = DataBase()
        if options.insert:
            db.insert(options.insert)
        if options.delete:
            db.delete(options.delete)
        if options.query:
            for i in db.query():
                print i
    else:
        print "Webstatus may not be installed: domains.db not found"

if __name__ == '__main__':
    main()
